<template>
  <el-dialog
    center
    v-if="isShow"
    v-dialogDrag
    :title="title"
    v-loading="loading"
    :width="dialogWidth"
    :before-close="close"
    :visible.sync="isShow"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="right"
      class="overflow pl15 pr15"
    >
      <el-row type="flex" justify="space-around">
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item
            class="required"
            prop="roomType"
            label="房型名称："
            v-if="!detailDialog"
            :label-width="labelWidth"
          >
            <el-input
              class="floor"
              autocomplete="off"
              v-model="form.roomType"
              placeholder="请输入房型名称"
            ></el-input>
          </el-form-item>
          <el-form-item
            v-if="detailDialog"
            label="房型名称："
            prop="roomType"
            :label-width="labelWidth"
          >
            <span>{{ form.roomType }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item
            prop="area"
            class="required"
            label="面积大小："
            v-if="!detailDialog"
            :label-width="labelWidth"
          >
            <el-input
              class="floor"
              v-model="form.area"
              autocomplete="off"
              placeholder="请输入面积大小"
            >
              <template>
                <slot slot="suffix" class>㎡</slot>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="detailDialog"
            label="面积大小："
            prop="area"
            :label-width="labelWidth"
          >
            <span>{{ form.area }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item
            v-if="!detailDialog"
            label="总套数："
            prop="count"
            :label-width="labelWidth"
            class="required"
          >
            <el-input
              class="floor"
              type="number"
              autocomplete="off"
              v-model="form.count"
              placeholder="请输入总套数"
            >
              <template>
                <slot slot="suffix" class>套</slot>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="detailDialog"
            label="总套数："
            prop="count"
            :label-width="labelWidth"
          >
            <span>{{ form.count }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb15 form-inp">
          <el-form-item
            v-if="!detailDialog"
            label="价格："
            prop="price"
            :label-width="labelWidth"
            class="required"
          >
            <el-input
              class="floor"
              type="number"
              autocomplete="off"
              v-model="form.price"
              placeholder="请输入价格"
            >
              <template>
                <slot slot="suffix" class>元/月</slot>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item
            v-if="detailDialog"
            label="价格："
            prop="price"
            :label-width="labelWidth"
          >
            <span>{{ form.price }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col v-if="!detailDialog" :span="24" class="mb15 form-inp">
          <el-form-item label="房屋配置：" :label-width="labelWidth">
            <el-button
              style="width: 120px;"
              class="theme-btn"
              @click="handleCheckAll"
              >全选/反选</el-button
            >
          </el-form-item>
          <el-form-item prop="supportingFacilities" :label-width="labelWidth">
            <el-checkbox-group v-model="supportingFacilities">
              <el-checkbox-button
                class="mt10"
                :key="item.number"
                :label="item.number"
                ref="supportingFacilities"
                name="supportingFacilities"
                v-for="item in roomSupportingFacilitiesTypeList"
                >{{ item.name }}</el-checkbox-button
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col v-if="detailDialog" :span="24" class="mb15 form-inp">
          <el-form-item label="房屋配置：" :label-width="labelWidth">
            <el-checkbox-group v-model="supportingFacilities">
              <el-checkbox-button
                class="mt10"
                disabled
                :key="item.number"
                :label="item.number"
                name="supportingFacilities"
                v-for="item in roomSupportingFacilitiesTypeList"
                >{{ item.name }}</el-checkbox-button
              >
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" justify="space-around">
        <el-col v-if="!detailDialog" :span="24" class="mb15">
          <el-form-item
            label="房间图片："
            :label-width="labelWidth"
            class="required"
          >
            <Thumbnail
              @deleteUserAvatar="handleDeleteUserAvatar"
              :photos="photoArr"
            ></Thumbnail>
            <ImageUpload
              :pegs="pegs"
              :limit="limit"
              :imageMaxSize="imageMaxSize"
              @uploadFiles="handleUploadFiles"
            ></ImageUpload>
          </el-form-item>
        </el-col>
        <el-col v-if="detailDialog" :span="24" class="mb15">
          <el-form-item label="房间图片：" :label-width="labelWidth">
            <img
              alt
              width="100%"
              :key="index"
              :src="photo"
              @click="handleShowPic(photo)"
              v-for="(photo, index) in photoList"
              class="thumbnail inline-block ml15 pointer"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span
      v-if="!detailDialog"
      slot="footer"
      class="dialog-footer align-center tiling inline-block"
    >
      <el-button @click="close">取 消</el-button>
      <el-button class="theme-btn" @click="handleConfirm('form')"
        >保 存</el-button
      >
    </span>
    <span
      v-if="detailDialog"
      slot="footer"
      class="dialog-footer align-center tiling inline-block"
    >
      <el-button @click="close">返 回</el-button>
    </span>
    <PhotoDialog
      @showPic="handleShowPic"
      :showPic="showPic"
      :isShowPic="isShowPic"
    ></PhotoDialog>
  </el-dialog>
</template>

<script>
import "@/utils/drag.js";
import Thumbnail from "@/components/thumbnail";
import { vlength } from "@/utils/verification.js";
import ImageUpload from "@/components/image_upload";
import PhotoDialog from "@/components/photo_dialog";
import { getAllDictionary } from "@/apis/dictionary";
import { addApartmentDetail, editApartmentDetail } from "@/apis/business";

export default {
  name: "Apartment_detail_dialog",
  data() {
    return {
      form: {
        area: "",
        count: "",
        price: "",
        photos: "",
        roomType: ""
      },
      limit: 3,
      pegs: [],
      showPic: "",
      photoArr: [],
      checkAll: [],
      tableData: [],
      isShowPic: false,
      imageMaxSize: 1024,
      uploadFileList: [],
      labelWidth: "125px",
      dialogWidth: "980px",
      supportingFacilities: [],
      roomSupportingFacilitiesTypeList: [],
      rules: {
        roomType: {
          validator: vlength(2, 10, "请输入房型名称"),
          trigger: "blur"
        },
        area: {
          validator: vlength(1, 5, "请输入面积大小"),
          trigger: "blur"
        },
        count: {
          validator: vlength(1, 3, "请输入总套数"),
          trigger: "blur"
        },
        price: {
          validator: vlength(2, 8, "请输入价格"),
          trigger: "blur"
        }
      }
    };
  },
  computed: {
    photoList() {
      return this.form.photos ? this.form.photos.split(",") : [];
    },
    isShow() {
      return (
        this.addDialog ||
        this.editDialog ||
        this.detailDialog ||
        this.addDetailDialog
      );
    }
  },
  mounted() {
    this.getSupportingFacilitiesList();
  },
  watch: {
    editDialog() {
      this.editDialog && this.transmit();
    },
    addDialog() {
      this.addDialog && this.resetForm();
    },
    detailDialog() {
      this.detailDialog && this.transmit();
    }
  },
  methods: {
    handleDeleteUserAvatar(delUrl) {
      this.photoArr.forEach((item, index) => {
        if (item === delUrl) {
          this.photoArr[index] = `D${item}`;
          this.pegs = this.pegs.filter(item => item !== delUrl);
        }
      });
    },
    handleUploadFiles(props) {
      this.uploadFileList = props;
    },
    handleShowPic(data) {
      this.showPic = data;
      this.isShowPic = !this.isShowPic;
    },
    transmit() {
      this.form = {
        area: this.apartmentDetailForm.area,
        count: this.apartmentDetailForm.count,
        price: this.apartmentDetailForm.price,
        photos: this.apartmentDetailForm.photos,
        roomType: this.apartmentDetailForm.roomType
      };
      const lists = this.apartmentDetailForm.supportingFacilitiesIds.split(",");
      this.supportingFacilities = lists.map(list => +list);
      this.photoArr = this.form.photos.split(",");
      this.pegs = JSON.parse(JSON.stringify(this.photoArr));
    },
    async getSupportingFacilitiesList() {
      const { rows } = await getAllDictionary({
        fieldName: "roomSupportingFacilitiesType"
      });
      this.checkAll = rows ? rows.map(item => item.number) : [];
      this.roomSupportingFacilitiesTypeList = rows;
    },
    handleCheckAll() {
      if (this.supportingFacilities.length) {
        //反选
        const obj = {};
        const formerChecked = this.supportingFacilities;
        formerChecked.forEach(item => (obj[item] = item));
        // 之前选中的Array类型转为Object类型
        this.supportingFacilities = this.checkAll.filter(
          item => item !== obj[item]
        );
        // 筛选出反选的
      } else {
        // 全选
        this.supportingFacilities = this.checkAll;
      }
    },
    handleConfirm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.editDialog
            ? this.editApartmentDetail()
            : this.addApartmentDetail();
        }
      });
    },
    addApartmentDetail() {
      const formData = new FormData();
      const files = this.uploadFileList;
      const rows = files.map(item => item.raw);

      if (!this.uploadFileList.length && !this.pegs.length) {
        return this.$notify.error({
          title: "错误",
          message: "请先上传房型图片！"
        });
      }

      if (rows) {
        rows.forEach(row => {
          formData.append("files", row);
        });
      }

      formData.append(
        "supportingFacilitiesIds",
        this.supportingFacilities.join(",")
      );
      formData.append("area", this.form.area);
      formData.append("count", this.form.count);
      formData.append("price", this.form.price);
      formData.append("roomType", this.form.roomType);
      formData.append("apartmentId", sessionStorage.getItem("apartmentId"));

      this.$store.dispatch("load/setLoading", true);
      // addApartmentDetail(formData).then(res => {
      //   this.$emit("update");
      //   this.$emit("close");
      //   this.$notify({
      //     title: res.msg,
      //     type: "success"
      //   });
      // });
      this.$emit("update");
      this.$emit("close");
      this.$notify({
        title: "操作成功！",
        type: "success"
      });
    },
    editApartmentDetail() {
      const formData = new FormData();
      const files = this.uploadFileList;
      const rows = files.map(item => item.raw);

      if (!this.uploadFileList.length && !this.pegs.length) {
        return this.$notify.error({
          title: "错误",
          message: "请先上传房型图片！"
        });
      }

      if (rows) {
        rows.forEach(row => {
          formData.append("files", row);
        });
      }

      formData.append(
        "supportingFacilitiesIds",
        this.supportingFacilities.join(",")
      );
      formData.append("area", this.form.area);
      formData.append("count", this.form.count);
      formData.append("price", this.form.price);
      formData.append("roomType", this.form.roomType);
      formData.append("photos", this.photoArr.join(","));
      formData.append("id", +this.apartmentDetailForm.id);
      formData.append("apartmentId", sessionStorage.getItem("apartmentId"));

      this.$store.dispatch("load/setLoading", true);
      // editApartmentDetail(formData).then(res => {
      //   this.$emit("update");
      //   this.$emit("close");
      //   this.$notify({
      //     title: res.msg,
      //     type: "success"
      //   });
      // });
      this.$emit("update");
      this.$emit("close");
      this.$notify({
        title: "操作成功！",
        type: "success"
      });
    },
    close() {
      this.$emit("close");
      this.resetForm();
    },
    resetForm() {
      this.form = {
        name: "",
        address: "",
        content: ""
      };
      this.photoArr = [];
      this.pegs.length = [];
      this.uploadFileList = [];
      this.supportingFacilities = [];
    }
  },
  components: {
    Thumbnail,
    ImageUpload,
    PhotoDialog
  },
  props: [
    "title",
    "loading",
    "addDialog",
    "editDialog",
    "detailDialog",
    "addDetailDialog",
    "apartmentDetailForm"
  ]
};
</script>

<style scoped></style>
